import { ObjectId } from 'mongodb'
import * as db from '../db'
import { stats } from '../stats'
import * as crypto from 'crypto'

import { Identity, IUser } from '../types'
import { sha } from './tools'

/*
  管理者api
*/

// 登录
export async function login(record: IUser) {
  const user = await db.userCollection.findOne({
    username: record.username
  })
  if (!user) throw stats.ERR_NOT_FOUND
  const pass = sha(record.password)
  if (!user || pass !== user.password) throw stats.ERR_LOGIN_FAILED
  const token = crypto.randomBytes(12).toString('hex')
  await db.tokenCollection.insertOne({
    _id: null,
    userToken: token,
    userId: user._id,
    createdAt: new Date()
  })
  return {
    token,
    user
  }
}

// 获得待审核书籍(兼顾筛选功能)
export async function judgelist(value: any) {
  const { skip, limit } = value
  const list = await db.booksCollection
    .find(
      {
        putaway: false,
        isDelete: false,
        judger: null
      },
      {
        sort: { updateAt: -1 },
        skip: skip,
        limit: limit,
        projection: {
          banner: 1,
          title: 1,
          lowprice: 1,
          allstock: 1,
          putaway: 1,
          isDelete: 1,
          judger: 1,
          judgeCon: 1
        }
      }
    )
    .toArray()
  const total = await db.booksCollection
    .find({ putaway: false, isDelete: false })
    .count()
  return { list, total }
}

export async function books(value: any) {
  const { skip, limit, search } = value
  const filterText = search
    ? {
        $or: [
          { title: { $regex: search } },
          { bookinfo: { $regex: search } },
          { books: { $elemMatch: { bookname: { $regex: search } } } }
        ]
      }
    : undefined
  const list = await db.booksCollection
    .find(
      { ...filterText },
      {
        sort: { updateAt: -1 },
        skip: skip,
        limit: limit,
        projection: {
          banner: 1,
          title: 1,
          lowprice: 1,
          allstock: 1,
          putaway: 1,
          isDelete: 1,
          judger: 1,
          judgeCon: 1
        }
      }
    )
    .toArray()
  const total = await db.booksCollection.find({ ...filterText }).count()
  return { list, total }
}

// 上架下架
export async function launch(userId: ObjectId, value: any) {
  const { bookId, putaway, content } = value
  const res = await db.booksCollection.findOneAndUpdate(
    { _id: new ObjectId(bookId) },
    { $set: { putaway, judger: userId, judgeCon: content } }
  )
  return res.value
}

export async function remarks(value: any) {
  const { skip, limit } = value
  const list = await db.remarksCollection
    .find({}, { sort: { createAt: -1 }, skip: skip, limit: limit })
    .toArray()
  const total = await db.remarksCollection.find().count()
  return { list, total }
}

// 控制评论, 但是在他的动态还是能看到评论
export async function control(remId: string, isDelete: boolean) {
  const res = await db.remarksCollection.findOneAndUpdate(
    { _id: new ObjectId(remId) },
    { $set: { isDelete } }
  )
  return res.value
}

export async function users(value: any) {
  const { skip, limit, search } = value
  const filterText = search
    ? {
        $or: [
          { nickname: { $regex: search } },
          { username: { $regex: search } },
          { signature: { $regex: search } }
        ]
      }
    : undefined
  const list = await db.userCollection
    .find({ ...filterText }, { skip, limit })
    .toArray()
  const total = await db.userCollection.find({ ...filterText }).count()
  return { list, total }
}

// 处理用户,设置管理员啥的
export async function dealuser(userId: string, role: Identity) {
  const res = await db.userCollection.findOneAndUpdate(
    { _id: new ObjectId(userId) },
    { $set: { role } }
  )
  return res.value
}

// 书籍详情
export async function detail(bookId: string) {
  const _id = new ObjectId(bookId)
  const book = await db.booksCollection.findOne({ _id })
  const judger = await db.userCollection.findOne({ _id: book.judger })
  const user = await db.userCollection.findOne({ _id: book.publisher })
  return { book: { ...book, judger: judger?.nickname }, user: { ...user } }
}
